package org.practice.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.practice.dao.ShopDaoFactory;
import org.practice.dao.ProductDao;
import org.practice.model.Product;
import org.practice.util.DaoException;

/**
 * 封装购物车的业务逻辑
 * 该对象为BO(Business-Object),用来封装业务逻辑的java对象,通过调用DAO(database-access-object)方法,
 * 结合PO(persistent-object),VO(value-object/view-object),DTO(data-transfer-object)进行业务操作。 
 */
public class CartService implements java.io.Serializable{
	private static final long serialVersionUID = 1234567L;
	private static Logger logger = Logger.getLogger(CartService.class);

	private Integer userId;

	// CartItem.product.id
	private Map<Integer, CartItemBO> cartItems;

	/**
	 * 
	 * @param user
	 */
	public CartService(Integer userId) {
		this.userId = userId;
		cartItems = new HashMap<Integer, CartItemBO>();
	}

	public Integer getUserId() {
		return userId;
	}

	/**
	 * 
	 * @param product
	 * @return
	 */
	public boolean addCartItem(Integer productId) throws DaoException {
		if (!cartItems.containsKey(productId)) {
			ProductDao productDao = ShopDaoFactory.createProductDao();
			Product product = productDao.findProductById(productId);
			CartItemBO item = new CartItemBO();
			item.setProduct(product);
			item.setDrop(false);
			item.setNumber(1);
			cartItems.put(product.getId(), item);
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @param productId
	 * @param num
	 * @return
	 */
	public boolean updateNum(Integer productId, int num) {
		if (cartItems.containsKey(productId)) {
			if (num <= 0) {
				return this.drop(productId);
			}
			CartItemBO item = cartItems.get(productId);
			item.setNumber(num);
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @param productId
	 * @return
	 */
	public boolean drop(Integer productId) {
		if (cartItems.containsKey(productId)) {
			CartItemBO item = cartItems.get(productId);
			item.setDrop(true);
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @param productId
	 * @return
	 */
	public boolean recovery(Integer productId) {
		if (cartItems.containsKey(productId)) {
			CartItemBO item = cartItems.get(productId);
			item.setDrop(false);
			return true;
		}
		return false;
	}

	/**
	 * 
	 */
	public void clear() {
		cartItems.clear();
	}

	

	/**
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		return cartItems.isEmpty();
	}

	/**
	 * 
	 * @return
	 */
	public List<CartItemBO> getCartItems() {
		List<CartItemBO> list = new ArrayList<CartItemBO>();
		Iterator<Integer> it = cartItems.keySet().iterator();
		while (it.hasNext()) {
			CartItemBO item = cartItems.get(it.next());
			if (!item.isDrop()) {
				list.add(item);
			}
		}
		return list;
	}

	/**
	 * 
	 * @return
	 */
	public List<CartItemBO> getDropCartItems() {
		List<CartItemBO> list = new ArrayList<CartItemBO>();
		Iterator<Integer> it = cartItems.keySet().iterator();
		while (it.hasNext()) {
			CartItemBO item = cartItems.get(it.next());
			if (item.isDrop()) {
				list.add(item);
			}
		}
		return list;
	}

	/**
	 * 
	 * @return
	 */
	public double getTotalPrice() {
		double totalPrice = 0;
		Iterator<Integer> it = cartItems.keySet().iterator();
		while (it.hasNext()) {
			CartItemBO item = cartItems.get(it.next());
			if (!item.isDrop()) {
				totalPrice += item.getProduct().getFixedPrice()
						* item.getNumber();
			}
		}
		return totalPrice;
	}

	/**
	 * 
	 * @return
	 */
	public double getDangPrice() {
		double dangPrice = 0;
		Iterator<Integer> it = cartItems.keySet().iterator();
		while (it.hasNext()) {
			CartItemBO item = cartItems.get(it.next());
			if (!item.isDrop()) {
				dangPrice += item.getProduct().getDangPrice()
						* item.getNumber();
			}
		}
		return dangPrice;
	}
	
	/**
	 * 鎶婅喘鐗╄溅鐨勪俊鎭浆鎹负瀛楃涓诧紝鐢ㄤ簬Cookie瀛樺劜
	 * @throws UnsupportedEncodingException
	 */
	public String serialize() {
		StringBuilder buffer = new StringBuilder();
		buffer.append(userId).append("@");
		if (cartItems.isEmpty()) {
			buffer.append("0");
		} else {
			Iterator<Integer> it = cartItems.keySet().iterator();
			while (it.hasNext()) {
				Integer productId = it.next();
				int num = cartItems.get(productId).getNumber();
				boolean drop = cartItems.get(productId).isDrop();
				buffer.append(productId + "," + num + "," + drop);
				buffer.append(";");
			}
		}
		if (buffer.length() > 0)
			buffer.deleteCharAt(buffer.length() - 1);
		logger.debug(buffer);

		return buffer.toString();
	}

	/**
	 * 
	 * @param content
	 * @throws DaoException
	 * @throws UnsupportedEncodingException
	 */
	public void load(String content) {
		this.cartItems.clear();
		String userId = content.substring(0, content.indexOf("@"));
		if (userId != null && Integer.parseInt(userId) == this.userId) {
			content = content.substring(content.indexOf("@") + 1);
			if (content == null || "0".equals(content))
				return;
			if (content != null && content.length() > 0) {
				String[] itemsArry = content.split(";");
				for (int i = 0; i < itemsArry.length; i++) {
					String[] itemArry = itemsArry[i].split(",");
					logger.debug(Arrays.toString(itemArry));
					Integer id = Integer.valueOf(itemArry[0]);
					int number = Integer.parseInt(itemArry[1]);
					boolean drop = Boolean.parseBoolean(itemArry[2]);
					
					ProductDao productDao = ShopDaoFactory.createProductDao();
					Product product = productDao.findProductById(id);
					CartItemBO item = new CartItemBO();
					item.setProduct(product);
					item.setNumber(number);
					item.setDrop(drop);
					cartItems.put(product.getId(), item);
					logger.debug(cartItems);
				}
			}
		}
	}
}
